package com.jiliang.common.exception.handle;

import com.jiliang.common.exception.business.DataException;
import com.jiliang.common.exception.business.LoginException;
import com.jiliang.common.exception.business.ServerServiceException;
import com.jiliang.common.exception.business.ValidationException;
import com.jiliang.common.result.Errors;
import com.jiliang.common.result.WebResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/***
 * 错误监听
 */
@RestControllerAdvice

public class GlobalExceptionHandler {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @ExceptionHandler
    public WebResult exceptionHandler(DataException ex){
        log.error("异常信息：{}", ex.getMessage());
        return WebResult.fail(ex.getCode(),ex.getException(),ex.getMsg(),ex.getObject());
    }

    @ExceptionHandler
    public WebResult exceptionHandler(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        StringBuilder sb = new StringBuilder("参数校验失败:");
        for (FieldError fieldError : result.getFieldErrors()) {
            sb.append(fieldError.getDefaultMessage()).append(";");
        }
        String msg = sb.toString();
        return WebResult.fail(Errors.SYSTEM_REQUEST_PARAM_ERROR,msg);
    }

    @ExceptionHandler
    public WebResult<Object> exceptionHandler(ServerServiceException e){
        log.error(e.getMessage() + ":" + e.getObject());
        return WebResult.fail(e.getCode(),e.getException(),e.getMsg(),e.getObject());
    }

    @ExceptionHandler
    public WebResult<Object> exceptionHandler(ValidationException e){
        log.error(e.getMessage() + ":" + e.getObject());
        return WebResult.fail(e.getCode(),e.getException(),e.getMsg(),e.getObject());
    }

    @ExceptionHandler
    public WebResult<Object> exceptionHandler(LoginException e){
        log.error(e.getMessage() + ":" + e.getObject());
        return WebResult.fail(e.getCode(),e.getException(),e.getMsg(),e.getObject());
    }
}
